#pragma once
#include <iostream>
#include <functional>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "InetAddr.hpp"
#include "ThreadPool.hpp"

using namespace ThreadPoolModual;

const static uint16_t defaultport = 8888;

// 线程池的任务
using task_t = std::function<void()>;
// 添加用户
using adduser_t = std::function<void(InetAddr &user)>;
// 轮询任务
using route_t = std::function<void(int sockfd, std::string message)>;
// 删除用户
using deletuser_t = std::function<void(InetAddr &user)>;

class UDPSever
{
public:
    UDPSever(uint16_t port = defaultport) : _in_addr(port), _isrunning(false)
    {
        // 1. 创建套接字
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error";
            exit(1);
        }
        LOG(LogLevel::DEBUG) << "socket succeed";

        // 2. 绑定
        int n = ::bind(_sockfd, _in_addr.NetAddr(), _in_addr.Len());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            exit(2);
        }
        LOG(LogLevel::DEBUG) << "bind succeed";
    }
    // 需要注入的任务序列
    void Regester(adduser_t add_user, route_t route, deletuser_t deletuser)
    {
        _add_user = add_user;
        _route = route;
        _delet_user = deletuser;
    }
    void Run()
    {
        _isrunning = true;
        char buff[1024];

        // 定义接收发送消息的主机的addr信息的结构
        struct sockaddr_in src_addr;
        socklen_t len = sizeof(src_addr);
        while (true)
        {
            // 接收来自客户端的信息
            int n = ::recvfrom(_sockfd, buff, sizeof(buff) - 1, 0, (struct sockaddr *)&src_addr, &len);
            if (n > 0)
            {
                InetAddr cli(src_addr);
                buff[n] = '\0';

                std::string message;
                if (strcmp(buff, "quit") == 0)
                {
                    _delet_user(cli);
                    message=cli.Addr()+" 我走了，你们聊";
                }
                else
                {
                    // 添加用户
                    _add_user(cli);
                    // 合成新的信息
                    message = cli.Addr() + "say #" + buff;
                }
                // 需要执行的任务就是User.hpp中的Router
                task_t task = std::bind(_route, _sockfd, message);
                // 让线程池进程调度轮转
                ThreadPool<task_t>::GetInstance()->Enqueue(task);
            }
        }
        _isrunning = false;
    }
    ~UDPSever()
    {
        close(_sockfd);
    }

private:
    int _sockfd;
    InetAddr _in_addr; // 用InetAddr 来管理转化操作
    bool _isrunning;
    adduser_t _add_user;
    route_t _route;
    deletuser_t _delet_user;
};
